<?php
require_once APP_PATH."library/sms/SignatureHelper.php";
use Aliyun\DySDKLite\SignatureHelper;

class sms_service extends service {
    protected $result;

    public function _initialize() {
		$this->vcode_table = $this->load->table('vcode');
        $this->model = $this->load->table('member/member');
    }

    public function post_vcode($params,$action = '', $type=0){
        $data = array();
        $data['vcode'] = random(4,1);
        $data['mobile'] = $params['mobile'];
        $data['mid'] = $params['mid'] ? $params['mid'] : 0;
        $data['action'] = $action;
        $data['dateline'] = TIMESTAMP;
        $result = $this->load->table('vcode')->update($data);
        if(!$result){
            return false;
        }else{
			$this->send_sms($data['mobile'], $data['vcode']);			
            if($action == 'register_validate'){
                runhook('register_validate',$data);
            }else{
                runhook('mobile_validate',$data);
            }
            return true;
        }
    }
	
	public function send_sms($mobile='', $vcode=''){
		$params = array ();
		$accessKeyId = "LTAIvYdDXgHlB8si";
		$accessKeySecret = "Zf5KkS51fjaQ0gHA90UcLRlfWHEphl";
		$params["PhoneNumbers"] = $mobile;
		$params["SignName"] = "安昕午托";
		$params["TemplateCode"] = "SMS_119075912";
		$params['TemplateParam'] = array (
			"code" => $vcode
		);	
		$params['OutId'] = random(5,1);
		$params['SmsUpExtendCode'] = random(7,1);
		if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
			$params["TemplateParam"] = json_encode($params["TemplateParam"]);
		}
		$helper = new SignatureHelper();
	
		// 此处可能会抛出异常，注意catch
		$content = $helper->request(
			$accessKeyId,
			$accessKeySecret,
			"dysmsapi.aliyuncs.com",
			array_merge($params, array(
				"RegionId" => "cn-hangzhou",
				"Action" => "SendSms",
				"Version" => "2017-05-25",
			))
		);
		return $content;
	}

	
}